import { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import router from '@/router'
import { defaultRoutes } from '@/router/routes/default-routes'
import { globalRoutes } from '@/router/routes/global-routes'
import { findRootPathRoute, generatorRoutes, mapTwoLevelRouter } from '../help'
import { constantRoutes } from '@/router/routes/constants'
import { getCurrentUserMenu } from '@/api/login'
import { OriginRoute } from '../types'

const usePermissionStore = defineStore('permission-route', {
  state: () => {
    return {
      permissionRoutes: [] as RouteRecordRaw[],
      menuList: [] as OriginRoute[],
    }
  },
  getters: {
    getPermissionSideBar(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden
      })
    },
    getMenuListSideBar(state) {
      return state.menuList.filter((it) => {
        return !it.hidden
      })
    },
    getPermissionSplitTabs(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden && it.children && it.children.length > 0
      })
    },
    getTopLevelTabs(state) {
      return state.permissionRoutes
        .filter((it) => {
          return it.meta && !it.meta.hidden && it.children && it.children.length > 0
        })
        .map((it) => {
          const obj = { ...it, items: it.children }
          delete obj.children
          return obj
        })
    },
  },
  actions: {
    // 暂时使用默认路由，动态路由待需求确认后添加
    async getRoutes() {
      const res: any = await getCurrentUserMenu()
      const list = [...globalRoutes, ...(res?.data || [])]
      // const list = [...globalRoutes, ...defaultRoutes]
      this.menuList = list

      const filterMenu = [
        {
          menuUrl: '/menuwrap',
          menuName: '',
          children: this.formatMenu(list),
        },
      ]
      return generatorRoutes(filterMenu)
    },
    // 暂时用于格式化路由批量导入ERP菜单设置
    formatDefault() {
      const list = JSON.parse(JSON.stringify(defaultRoutes))
      list.forEach((el: any) => {
        el.menuType = 1
        el.affix = false
        el.popUpsTitle = ''
        el.popUps = false
        el.hidden = el.hidden ? true : false
        el.funcList = []
        list?.children?.forEach((item: any) => {
          item.menuType = 2
          item.affix = false
          item.popUpsTitle = ''
          item.popUps = false
          item.hidden = item.hidden ? true : false
          item.funcList = []
          item?.children?.forEach((child: any) => {
            child.menuType = 3
            child.affix = false
            child.popUpsTitle = ''
            child.popUps = false
            child.hidden = child.hidden ? true : false
            child.funcList = []
          })
        })
      })
      return list
    },
    // 格式化菜单
    formatMenu(allMenus: Array<OriginRoute>) {
      const menus: Array<OriginRoute> = []
      function filterMenu(list: Array<OriginRoute>) {
        list.forEach((el: OriginRoute) => {
          if (el.menuUrl) {
            menus.push(el)
          }
          if (el.children && el.children.length) {
            filterMenu(el.children)
          }
        })
      }
      filterMenu(allMenus)
      return menus
    },

    async initPermissionRoute() {
      // 加载路由
      const accessRoutes = await this.getRoutes()
      const mapRoutes = mapTwoLevelRouter(accessRoutes)
      mapRoutes.forEach((it: any) => {
        router.addRoute(it)
      })
      // 配置 `/` 路由的默认跳转地址
      router.addRoute({
        path: '/',
        redirect: findRootPathRoute(accessRoutes),
        meta: {
          hidden: true,
        },
      })
      // 这个路由一定要放在最后
      router.addRoute({
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        meta: {
          hidden: true,
        },
      })
      this.permissionRoutes = [...constantRoutes, ...accessRoutes]
    },
    isEmptyPermissionRoute() {
      return !this.permissionRoutes || this.permissionRoutes.length === 0
    },
    reset() {
      this.$reset()
    },
  },
})

export default usePermissionStore
